﻿namespace EasyWeb.Validation
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Globalization;
    using System.Linq;

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class EWSystemPrefixValidationAttribute : ValidationAttribute
    {
        public override string FormatErrorMessage(string name)
        {
            return string.Format(CultureInfo.CurrentCulture, EWValidationResources.Validation_SystemPrefix, name);
        }

        public override bool IsValid(object value)
        {
            var text = value as string;

            if (!string.IsNullOrEmpty(text))
            {
                const string ALL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

                return !(text.StartsWith("ew", StringComparison.OrdinalIgnoreCase) ||
                         text.StartsWith("easyweb", StringComparison.OrdinalIgnoreCase) ||
                         text.Any(item => ALL.IndexOf(item, 0, ALL.Length) < 0));
            }

            return false;
        }
    }
}
